package com.sfh.cpc.user.model;

import com.sfh.cpc.com.BaseAppContent;
import com.sfh.cpc.com.CacheCity;
import com.sfh.cpc.com.entity.ECity;
import com.sfh.cpc.com.entity.EUser;
import com.sfh.cpc.com.entity.RspBase;
import com.sfh.cpc.com.req.ReqFile;
import com.sfh.cpc.com.req.ReqUserRegister;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.exception.HandleException;
import com.sfh.lib.mvvm.service.BaseViewModel;
import com.sfh.lib.rx.IResult;
import com.sfh.lib.rx.IResultSuccess;

import java.util.List;

import io.reactivex.functions.Function;

/**
 * 功能描述: 注册
 *
 * @author SunFeihu 孙飞虎
 * @date 2018/8/17
 */
public class RegisterModel extends BaseViewModel  {

    public void fileSave(String loanPath) {

        this.execute(new ReqFile(loanPath), new IResult<RspBase<String>>() {
            @Override
            public void onFail(HandleException e) {
                setValue("onSaveFile");
                showToast(e.getMsg());
            }

            @Override
            public void onSuccess(RspBase<String> data) throws Exception {
                setValue("onSaveFile", data);
            }
        });
    }

    public void queryCiry() {
        this.execute(new CacheCity().queryCity(), new IResult<List<ECity>>() {
            @Override
            public void onSuccess(List<ECity> data) throws Exception {
                setValue("selectCity", data);
            }

            @Override
            public void onFail(HandleException e) {
                showToast(e.getMsg());
            }
        });
    }

    /***
     * 注册
     * @param req
     */
    public void save(ReqUserRegister req) {

        this.execute(false, req.getTask().map(new Function<RspBase<EUser>, RspBase<EUser>>() {
            @Override
            public RspBase<EUser> apply(RspBase<EUser> eUserRspBase) throws Exception {
                // 缓存数据
                if (eUserRspBase.success()) {
                    AppCacheManager.putCache(BaseAppContent.USER, eUserRspBase.getData(), true);
                }
                return eUserRspBase;
            }
        }), new IResultSuccess<RspBase<EUser>>() {
            @Override
            public void onSuccess(RspBase<EUser> rspBase) throws Exception {
               setValue("onSave", rspBase);
            }
        });
    }
}
